package landlords.client.event;

import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import landlords.channel.ChannelUtils;
import landlords.enums.ClientEventCode;
import landlords.enums.ServerEventCode;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

public abstract class ClientEventListener {
    public abstract void call(Channel channel, String data);
    public final static Map<ClientEventCode,ClientEventListener> LISTENER_MAP=new HashMap<>();
    private final static String LISTENER_PREFIX="landlords.client.event.ClientEventListener_";

    public static ClientEventListener get(ClientEventCode code){
        ClientEventListener listener;
        //首先在容器里找该事件处理器是否已被装入容器
        if(ClientEventListener.LISTENER_MAP.containsKey(code)){
            listener=ClientEventListener.LISTENER_MAP.get(code);
        }
        else{
            String eventListener=LISTENER_PREFIX+code.toString().toUpperCase(Locale.ROOT);
            //创建新的listener对象，并将其加入容器LISTENER_MAP中，这里为什么不直接使用new来创建对象呢？？？
            Class<ClientEventListener> eventListenerClass= null;
            try {
                //由于事先不知道到底该创建哪一个对象，因此利用反射机制确认
                eventListenerClass = (Class<ClientEventListener>) Class.forName(eventListener);
                listener=eventListenerClass.newInstance();
                ClientEventListener.LISTENER_MAP.put(code,listener);
                return listener;
            } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
                throw new RuntimeException(e);
            }

        }

        return null;
    }
    protected ChannelFuture pushToServer(Channel channel, ServerEventCode code, String datas){
        return ChannelUtils.pushToServer(channel,code,datas);
    }
    protected ChannelFuture pushToServer(Channel channel,ServerEventCode code){
        return ChannelUtils.pushToServer(channel,code,null);
    }
}
